<?php
/*
 * Created on Sep 9, 2011
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class CommonUtils {
	// $page: is the current page
	// $rp is results per page.
	// $total is the total number of results.
	// $limit is the number of page values want to display 
	// From: http://codeigniter.com/wiki/Flexible_Paging_Plugin/
    public function paging($page,$rp,$total,$limit)
	{
	        $limit -= 1;
	
	        $mid = floor($limit/2);
	        
	        if (is_numeric($total) && $total>$rp){
	        	$numpages = ceil($total/$rp);
	        } 
	        else
	            $numpages = 1;
	        
	        if ($page>$numpages) $page = $numpages;
	            $npage = $page;
			//$limit = $numpages;
	        while (($npage-1)>0&&$npage>($page-$mid)&&($npage>0))
	            $npage -= 1;
	        
	        $lastpage = $npage + $limit;
	        
	        if ($lastpage>$numpages) 
	            {
	            $npage = $numpages - $limit + 1;
	            if ($npage<0) $npage = 1;
	            $lastpage = $npage + $limit;
	            if ($lastpage>$numpages) $lastpage = $numpages;
	            }
	        
	        while (($lastpage-$npage)<$limit) $npage -= 1;        
	        
	        if ($npage<1) $npage = 1;
	        
	        //echo $npage; exit;
	        
	        $paging['first'] = 1;
	        if ($page>1) $paging['prev'] = $page - 1; else $paging['prev'] = 1;
	        $paging['start'] = $npage;
	        $paging['end'] = $lastpage;
	        $paging['page'] = $page;            
	        if (($page+1)<$numpages) $paging['next'] = $page + 1; else $paging['next'] = $numpages;
	        $paging['last'] = $numpages;
	        $paging['total'] = $total;
	        $paging['iend'] = $page * $rp;
	        $paging['istart'] = ($page * $rp) - $rp + 1;
	        
	        if (($page * $rp)>$total) $paging['iend'] = $total;
	        
	        return $paging;    
	}
	public function pagingHTML($pPaging=array(),$func='',$arg=array()){
		$strHTML='';
		$buildPaging = '';
		$pageStart = $pPaging['start'];
		$pageEnd = $pPaging['end'];
		$pageCur = $pPaging['page'];
		$strarg='';
		foreach($arg as $itemarg=>$itemvalue){
			$strarg .="'".$itemvalue."',";
		}
		$displayPaging = $pageEnd > 1 ? "visible":"hidden";
		if($pageStart==$pageCur){
			$buildPaging .= '<span class="pagnDisabled">&laquo Previous | Page:</span>';
		}else{
			$buildPaging .= '<a href="javascript:'.$func.'('.$strarg.$pPaging['prev'].')" title="Go to Previous Page"><span>&laquo Previous</span></a> | Page: ';
		}
		if ($pageCur >3 && $pageStart >1){
			$buildPaging .= '<a href="javascript:'.$func.'('.$strarg.'1)" title="Go to Page 1" name ="page" id="'. '1' .'"  class="page">1</a>...';
		}
		for ($i = $pageStart; $i <= $pageEnd; $i++)
		{
		    $current = ' ';
			if ($i==$pageCur){ $current = 'current'; }
			$content = $i==$pageEnd?($i==$pPaging['last']?$i."</span></a>":$i. "...</span></a>"):($i."</span></a>"."&nbsp;&nbsp;") ;
			$buildPaging .= '<a href="javascript:'.$func.'('.$strarg.$i.')" title="Go to Page '.$i.'" name = "'.$current.'page" id = "'.$i.'" class="'.$current.'page"><span>'.$content;
		}
		if($pageEnd==$pageCur){
			$buildPaging .=  " | Next &raquo;";
		}else{
			$buildPaging .= '<a href="javascript:'.$func.'('.$strarg.$pPaging['next'].')" title="Go to Last Page"><span> | Next &raquo;</span></a>';
		}
		return $buildPaging;
		
	}
	public function getNumberProductPerPage()
	{
		return 10;
	}
	public function getNumberPageDisplay()
	{
		return 5;
	}
	// mySQL don't understand 'dd/MM/yyyy' -> must change format to 'yyyy/MM/dd'
	// change from MM/dd/yyy to yyyy/MM/dd
	public function changeFormatDate1($strDate){
		//if(strlen($strDate)!=10) return false;
		try{
			$arr = array();
			$arr = explode('/', $strDate);//arr[0]: month,arr[1]: day,arr[2]: year
			if(count($arr)==3
				&& is_numeric($arr[0])
				&& is_numeric($arr[1])
				&& is_numeric($arr[2])
				&&checkdate($arr[0], $arr[1], $arr[2])){
				return $arr[2].'/'.$arr[0].'/'.$arr[1];
			}else{
				return " ";
			}
		}
		catch(Exception $e){
			return " ";
		}
		//return false;
	} 
	function getBrowser()
	{
		$u_agent = $_SERVER['HTTP_USER_AGENT'];
		$bname = 'Unknown';
		$platform = 'Unknown';
		$version= "";
		
		//First get the platform?
		if (preg_match('/linux/i', $u_agent)) {
		$platform = 'linux';
		}
		elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
		$platform = 'mac';
		}
		elseif (preg_match('/windows|win32/i', $u_agent)) {
		$platform = 'windows';
		}
		
		// Next get the name of the useragent yes seperately and for good reason
		if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
		{
		$bname = 'Internet Explorer';
		$ub = "MSIE";
		}
		elseif(preg_match('/Firefox/i',$u_agent))
		{
		$bname = 'Mozilla Firefox';
		$ub = "Firefox";
		}
		elseif(preg_match('/Chrome/i',$u_agent))
		{
		$bname = 'Google Chrome';
		$ub = "Chrome";
		}
		elseif(preg_match('/Safari/i',$u_agent))
		{
		$bname = 'Apple Safari';
		$ub = "Safari";
		}
		elseif(preg_match('/Opera/i',$u_agent))
		{
		$bname = 'Opera';
		$ub = "Opera";
		}
		elseif(preg_match('/Netscape/i',$u_agent))
		{
		$bname = 'Netscape';
		$ub = "Netscape";
		}
		
		// finally get the correct version number
		$known = array('Version', $ub, 'other');
		$pattern = '#(?<browser>' . join('|', $known) .
		')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
		if (!preg_match_all($pattern, $u_agent, $matches)) {
		// we have no matching number just continue
		}
		
		// see how many we have
		$i = count($matches['browser']);
		if ($i != 1) {
		//we will have two since we are not using 'other' argument yet
		//see if version is before or after the name
		if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
		$version= $matches['version'][0];
		}
		else {
		$version= $matches['version'][1];
		}
		}
		else {
		$version= $matches['version'][0];
		}
		
		// check if we have a number
		if ($version==null || $version=="") {$version="?";}
		
		return array(
		'userAgent' => $u_agent,
		'name' => $bname,
		'version' => $version,
		'platform' => $platform,
		'pattern' => $pattern
		);
	}
	
	public function getNumberOrderPerPage()
	{
		return 10;
	}
	
	public function getNumberUserPerPage()
	{
		return 10;
	}
	function objectToArray( $object )
	{
		if( !is_object( $object ) && !is_array( $object ) )
		{
			return $object;
		}
		if( is_object( $object ) )
		{
			$object = get_object_vars( $object );
		}
		return array_map( 'objectToArray', $object );
	}
	function getExtension($str) {
		$i = strrpos($str,".");
		if (!$i) {
			return "";
		}
		$l = strlen($str) - $i;
		$ext = substr($str,$i+1,$l);
		return $ext;
	}
	function checkValidExtension($filename, $fileExtentionReq){
		$result = false;
		if(!empty($filename)){
			$file_ext = $this->getExtension($filename);
			$result = stripos(",". $fileExtentionReq, $file_ext) > 0;
		}
		return $result;
	}
	function checkZipCode($strZipCode){
		if(is_numeric($strZipCode))
			return sprintf("%05s",$strZipCode);
		return '';
	}
	function validatephone($phone2=''){
		//$this->load->library('form_validation');
		if(strlen($phone2)<=0){
			return true;
		}
		$phone2=str_replace('-','',$phone2);
		if(strlen($phone2)!=7){
			return false;
		}else{
			return true;
		}
	}
	// convert from (yyy)xxx-xxxx to yyy;xxx-xxxx 
	function convertPhoneImport($phoneImport){
		if(strlen($phoneImport)<1) return'';
		
		$arrPhone = explode(')',$phoneImport);
		if(count($arrPhone)<2)return'';
		
		$phone1 = substr($arrPhone[0], 1);
		$phone2 = $this->validatephone(trim($arrPhone[1],' '))?trim($arrPhone[1],' '):'';
		return $phone1.';'.$phone2.';';		
	}
	public function delete_folder($tmp_path, $delete_folder = false){
	  //if(!is_writeable($tmp_path) && is_dir($tmp_path)){chmod($tmp_path,0777);}
	  $handle = opendir($tmp_path);
	  while($tmp=readdir($handle)){
	    if($tmp!='..' && $tmp!='.' && $tmp!=''){
	         if(is_writeable($tmp_path. "/" .$tmp) && is_file($tmp_path. "/" .$tmp)){
	         	 
         		if(substr(sprintf('%o', fileperms($tmp_path. "/" .$tmp)), -4)!='0444'){ //check permit delete
         			unlink($tmp_path. "/" .$tmp);
         		}
	         }elseif(!is_writeable($tmp_path. "/" .$tmp) && is_file($tmp_path. "/" .$tmp)){
	             //chmod($tmp_path. "/" .$tmp,0666);
	         	if(substr(sprintf('%o', fileperms($tmp_path. "/" .$tmp)), -4)!='0444'){ //check permit delete
	         		unlink($tmp_path. "/" .$tmp);
	         	}
	         }
	        
	         if(is_writeable($tmp_path. "/" .$tmp) && is_dir($tmp_path. "/" .$tmp)){
	                $this->delete_folder($tmp_path. "/" .$tmp, $delete_folder);
	         }elseif(!is_writeable($tmp_path. "/" .$tmp) && is_dir($tmp_path. "/" .$tmp)){
	                //chmod($tmp_path. "/" .$tmp,0777);
	                $this->delete_folder($tmp_path. "/" .$tmp, $delete_folder);
	         }
	    }
	  }
	  closedir($handle);
	  if($delete_folder) rmdir($tmp_path);
	  if(!is_dir($tmp_path)){return true;}
	  else{return false;}	
	}
	
	/**
     * A method to facilitate easy bulk inserts into a given table.
     * @param string $table_name
     * @param array $column_names A basic array containing the column names
     *  of the data we'll be inserting
     * @param array $rows A two dimensional array of rows to insert into the
     *  database.
     * @param bool $escape Whether or not to escape data
     *  that will be inserted. Default = true.
     * @author Kenny Katzgrau <katzgrau@gmail.com>
     */
    function insert_rows_query($table_name, $column_names, $rows, $escape = true)
    {
        /* Build a list of column names */
        $columns    = array_walk($column_names, array($this, 'prepare_column_name') );
        $columns    = implode(',', $column_names);

        /* Escape each value of the array for insertion into the SQL string */
        if( $escape ) array_walk_recursive( $rows, array( $this, 'escape_value' ) );
        
        /* Collapse each rows of values into a single string */
        $length = count($rows);
        for($i = 0; $i < $length; $i++) $rows[$i] = implode(',', $rows[$i]);
        /* Collapse all the rows into something that looks like
         *  (r1_val_1, r1_val_2, ..., r1_val_n),
         *  (r2_val_1, r2_val_2, ..., r2_val_n),
         *  ...
         *  (rx_val_1, rx_val_2, ..., rx_val_n)
         * Stored in $values
         */
        $values = "(" . implode( '),(', $rows ) . ")";

        $sql = "INSERT INTO $table_name ( $columns ) VALUES $values";

        return $sql;
    }

    function escape_value(& $value)
    {
        if( is_string($value) )
        {
            $value = "'" . mysql_real_escape_string($value) . "'";
        }else if($value == null){
        	$value = "NULL";
        }
    }

    function prepare_column_name(& $name)
    {
        $name = "`$name`";
    }
    
    function dateRange( $first, $last, $step = '+1 day', $format = 'Y/m/d' ) {
		$dates = array();
		$current = strtotime( $first );
		$last = strtotime( $last );
		while( $current <= $last ) {
			$dates[] = date( $format, $current );
			$current = strtotime( $step, $current );
		}

		return $dates;
	}
	function displayPDF($pdf, $disp){
		if ($disp !== "inline" && $disp !== "attachment") {
			throw new Exception("Invalid disposition.");
		}
		 
		$p = $pdf->contents;	
		if ($p !== false) {
			header("Content-Type: application/pdf");
			header("Content-Transfer-Encoding: binary");
			header("Content-Length: ".strlen($pdf->contents));
			header("Content-Disposition: $disp; filename=\"". $pdf->name."\"");
			header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1
			header('Pragma: no-cache'); // HTTP 1.0
			header('Expires: 0'); // Proxies
			
			//removes all printed/echoed items
			ob_end_clean();	
			flush();
			echo $p;
			exit;			
		}
	}
	
	function getRealPrice($productitem, $defaultAdjust, $ValueUsedForCalcSellingPrice, $options = array("getSalePrice" => true)){
		$realprice = 0;
		if(empty($productitem)) return $realprice;
		
		if(!isset($productitem->realPrice)) $productitem->realPrice = $productitem->price;
		if($productitem->seller_id==1){
			$adjustedcost = $productitem->realPrice * (1+$defaultAdjust/100);
			$adjustedcost=$adjustedcost > 0 ? $adjustedcost : 0;
			if($productitem->msrp!=null && $productitem->msrp>0){
				if($productitem->msrp<$adjustedcost){
					$adjustedcost=(($productitem->msrp-$productitem->realPrice)/3)+$productitem->realPrice;
				}
			}
			
			$sellingprice=$adjustedcost/$ValueUsedForCalcSellingPrice;
			
			if($productitem->map > $adjustedcost){
				$realprice = $productitem->map;
			}
			else{
				if($productitem->msrp > $adjustedcost){
					if($productitem->msrp > $sellingprice){
						$realprice = $sellingprice;
					}else{
						$realprice = $productitem->msrp;
					}
				} else $realprice = $sellingprice;
			}	
		}else{
			$realprice= $productitem->saleprice > 0 && $options['getSalePrice']? $productitem->saleprice : $productitem->realPrice;
		}
		
		return round($realprice, 2);
	}
	
//	function force_ssl($uri_string)
//    {
//        $CI =& get_instance();
//        $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
//        if ($_SERVER['SERVER_PORT'] != 443)
//        {
//        	if(empty($uri_string)) redirect($CI->uri->uri_string());
//        	else redirect($uri_string);
//        }
//    }
//    function force_nonssl($uri)
//    {
//        $CI =& get_instance();
//        $CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
//        if ($_SERVER['SERVER_PORT'] == 443)
//        {
//            if(empty($uri_string)) redirect($CI->uri->uri_string());
//        	else redirect($uri_string);
//        }
//    } 
	public function alphapagingHTML($alpha=-1,$func=''){
		$alphapagingdata = "";
		$alphapagingdata .='<div class="ln-letters">' .
								//'<a id = "aRecommended" href="javascript:'.$func.'(-2,1);" '.($alpha==-1?'class="_ ln-selected"':'class="_ ln-selected"').'><font color="red"><u>Recommended</u></font></a>' .
								'<a id = "aRecommended" href="javascript:'.$func.'(-1,1);" '.($alpha==-1?'class="_ ln-selected"':'class="_ ln-selected"').'><font color="red"><u>Recommended</u></font></a>' .
								'<a href="javascript:'.$func.'(\'^[0-9]\',1)" '.($alpha=='^[0-9]'?'class="_ ln-selected"':'class="_"').'>[0-9]</a><a href="javascript:'.$func.'(\'A\',1)" '.($alpha=='A'?'class="a ln-selected"':'class="a"').'>A</a>' .
							   '<a href="javascript:'.$func.'(\'B\',1)" '.($alpha=='B'?'class="b ln-selected"':'class="b"').'>B</a>' .
					           '<a href="javascript:'.$func.'(\'C\',1)" '.($alpha=='C'?'class="c ln-selected"':'class="c"').'>C</a>' .
					           '<a href="javascript:'.$func.'(\'D\',1)" '.($alpha=='D'?'class="d ln-selected"':'class="d"').'>D</a>' .
				           		'<a href="javascript:'.$func.'(\'E\',1)" '.($alpha=='E'?'class="e ln-selected"':'class="e"').'>E</a><a href="javascript:'.$func.'(\'F\',1)" '.($alpha=='F'?'class="f ln-selected"':'class="f"').'>F</a>' .
		           				'<a href="javascript:'.$func.'(\'G\',1)" '.($alpha=='G'?'class="g ln-selected"':'class="g"').'>G</a>' .
	   						    '<a href="javascript:'.$func.'(\'H\',1)" '.($alpha=='H'?'class="h ln-selected"':'class="h"').'>H</a><a href="javascript:'.$func.'(\'I\',1)" '.($alpha=='I'?'class="i ln-selected"':'class="i"').'>I</a>' .
					    		'<a href="javascript:'.$func.'(\'J\',1)" '.($alpha=='J'?'class="j ln-selected"':'class="j"').'>J</a>' .
					    		'<a href="javascript:'.$func.'(\'K\',1)" '.($alpha=='K'?'class="k ln-selected"':'class="k"').'>K</a>' .
					    		'<a href="javascript:'.$func.'(\'L\',1)" '.($alpha=='L'?'class="l ln-selected"':'class="l"').'>L</a>' .
					    		'<a href="javascript:'.$func.'(\'M\',1)" '.($alpha=='M'?'class="m ln-selected"':'class="m"').'>M</a>' .
					    		'<a href="javascript:'.$func.'(\'N\',1)" '.($alpha=='N'?'class="n ln-selected"':'class="n"').'>N</a>' .
					    		'<a href="javascript:'.$func.'(\'O\',1)" '.($alpha=='O'?'class="o ln-selected"':'class="o"').'>O</a>' .
					    		'<a href="javascript:'.$func.'(\'P\',1)" '.($alpha=='P'?'class="p ln-selected"':'class="p"').'>P</a>' .
					    		'<a href="javascript:'.$func.'(\'Q\',1)" '.($alpha=='Q'?'class="q ln-selected"':'class="q"').'>Q</a>' .
					    		'<a href="javascript:'.$func.'(\'R\',1)" '.($alpha=='R'?'class="r ln-selected"':'class="r"').'>R</a>' .
					    		'<a href="javascript:'.$func.'(\'S\',1)" '.($alpha=='S'?'class="s ln-selected"':'class="s"').'>S</a>' .
					    		'<a href="javascript:'.$func.'(\'T\',1)" '.($alpha=='T'?'class="t ln-selected"':'class="t"').'>T</a>' .
					    		'<a href="javascript:'.$func.'(\'U\',1)" '.($alpha=='U'?'class="u ln-selected"':'class="u"').'>U</a>' .
					    		'<a href="javascript:'.$func.'(\'V\',1)" '.($alpha=='V'?'class="v ln-selected"':'class="v"').'>V</a>' .
					    		'<a href="javascript:'.$func.'(\'W\',1)" '.($alpha=='W'?'class="w ln-selected"':'class="w"').'>W</a>' .
					    		'<a href="javascript:'.$func.'(\'X\',1)" '.($alpha=='X'?'class="x ln-selected"':'class="x"').'>X</a>' .
					    		'<a href="javascript:'.$func.'(\'Y\',1)" '.($alpha=='Y'?'class="y ln-selected"':'class="y"').'>Y</a>' .
					    		'<a href="javascript:'.$func.'(\'Z\',1)" '.($alpha=='Z'?'class="z ln-selected"':'class="z ln-last"').'>Z</a></div>';
		return $alphapagingdata;
	}
	// function check url exist.
	function urlExists($url=NULL)
	{
		 if($url == NULL) return false;
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 5);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$data = curl_exec($ch);
		$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		return $httpcode;
		/*
		if($httpcode>=200 && $httpcode<300){
			return true;
		} else {
			return false;
		}
		*/
	}
	// input: 1231234567 - output: 123-1234567
	function  formatPhone1($strPhone,$ext=""){
		if(strlen($strPhone)>7){ // have area code
				$strPhone = substr($strPhone,0,3)."-".substr($strPhone,3);
			}
		if ($ext!=""){
			$strPhone .= " Ext. ".$ext;
		}
		return $strPhone;
	}
	// input: 1231234567 - output: (123)123-4567
	function  formatPhone2($strPhone,$ext=""){
		if(strlen($strPhone)>7){ // have area code
				$strPhone1 = "(".substr($strPhone,0,3).")";
				$strPhone2 = substr($strPhone,3);
				if(strlen($strPhone2)==7)$strPhone2 = substr($strPhone2,0,3)."-".substr($strPhone2,3);
				$strPhone = $strPhone1.$strPhone2;
			}
		if ($ext!=""){
			$strPhone .= " Ext. ".$ext;
		}
		return $strPhone;
	}
	// input: YYYY/mm/dd h:m:s - output $full=true return YYYY/mm/ddTh:m:sZ or $full=false return YYYY/mm/ddT00:00:00Z
	function convertToSolrDateTime($str,$full=true){
		$arr = explode(" ",$str);
		$date = str_replace("/","-",$arr[0]);
		$time = "00:00:00.000";
		if(isset($arr[1]))$time = $arr[1];
		return $date."T".$time."Z";
	}
	
	function checkFullname($fullname){
		$rs = false;
		if(!empty($fullname)){
			$arr = explode(" ", trim($fullname));
			//no empty lastname
			$rs = !empty($arr[1]);
		}
		return $rs;
	}
	
	public function convertForUrl($name, $seperateChar = "-") {
		$name = strtolower($name);
		// replace character not alpha numeric by $seperate
		for ( $i = 0; $i < strlen($name); $i++ ) {
			if ( ($name[$i] < 'a' || $name[$i] > 'z') && !is_numeric($name[$i]) ) {
				$name[$i] = $seperateChar;
			}	
		}
		// remove "--"
		while(strpos($name, $seperateChar.$seperateChar)!==false) $name = str_replace($seperateChar.$seperateChar, $seperateChar,$name );
		return trim($name, $seperateChar);
	}
	function url_exists($url) {
		if(@file_get_contents($url,0,NULL,0,1))
		{
			return true;
		}
		else
		{ 
			return false;
		} 
	}
}
?>
